import axios from 'axios';


// function parseJSON(response) {
//   return response.json();
// }

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

export default function axiosRequest(url, options) {
  const defaultOptions = {
    timeout: 4000,
    dataType: 'json',
    mode: 'cors',
    responseType: 'json',
    withCredentials: true,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      token: 'eb6a6a00-55c8-11e8-97e4-13ca1ed2a4f7',
    },
  };
  if (url.indexOf('captcha') !== -1) {
    defaultOptions.headers.Accept = 'image/png';
    defaultOptions.responseType = 'arraybuffer';
  }

  const newOptions = { ...defaultOptions, ...options };

  newOptions.url = url;
  if ('method' in newOptions) {
    newOptions.method = newOptions.method.toUpperCase();
  } else {
    newOptions.method = 'GET';
  }

  if (newOptions.method !== 'GET') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.data = JSON.stringify(newOptions.body);
    } else {
      newOptions.data = newOptions.body;
    }
  } else {
    newOptions.params = newOptions.body;
  }

  return axios(newOptions)
    .then(checkStatus)
    .then((response) => {
      return response.data;
    })
    .catch(err => ({ err }));
}

